import React, { useState, useEffect, useRef } from "react";
import { Upload, Button } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import Luckyexcel from "luckyexcel";
import toolbarOptions from "./toolbarOptions";
import styles from "./index.module.less";

export default function ExcelPage() {
  function beforeUpload(file) {
    Luckyexcel.transformExcelToLucky(file, (exportJson) => {
      luckysheet.destroy();
      luckysheet.create({
        container: "luckysheetRef",
        title: exportJson.info.name,
        data: exportJson.sheets,
        lang: "zh", // 设定表格语言
        showtoolbarConfig: toolbarOptions,
      });
    });
    return false; // 阻止自动上传
  }

  const uploadProps = {
    name: "file",
    action: "", // 不需要实际的上传地址
    showUploadList: false,
    headers: {
      authorization: "authorization-text",
    },
    beforeUpload: beforeUpload,
  };

  useEffect(() => {
    const options = {
      container: "luckysheetRef",
      data: [
        {
          name: "Sheet1",
          color: "var(--PrimaryColor)",
          status: "1",
          order: "0",
          data: [],
          config: {},
          index: 0,
        },
      ],
      lang: "zh", // 设定表格语言
      showtoolbarConfig: toolbarOptions,
    };
    luckysheet.create(options);
  }, []);

  function saveFiles() {
    console.log(luckysheet.getAllSheets(), "保存数据");
  }

  return (
    <div className={styles.root}>
      <div className="excel-btn">
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />}>上传xlsx</Button>
        </Upload>
        <Button className="ml-10" type="primary" onClick={saveFiles}>
          保存
        </Button>
      </div>

      <div id="luckysheetRef" className="sheet-class"></div>
    </div>
  );
}
